package com.byzk.p2p.admin.base.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.alibaba.fastjson.JSONObject;
import com.byzk.p2p.admin.admin.vo.AdminUserVo;
import com.byzk.p2p.admin.admin.vo.SystemRole;

public class BaseController {

//	protected static String	SUCCESS = "success";
//	protected static String	FAIL = "fail";
//	protected static String	ERROR = "erroe";
	
	protected HttpServletRequest request;  
	protected HttpServletResponse response;  
    protected HttpSession session;
    
    /**
     * 根据当前的方法名称生成视图路径<br />
     * <p/>
     * 约定每个对应了 ftl 视图的 controller 需要在 view 下必须指定一个以 controller
     * 命名，但是所有字母转换为小写的目录（比如： {@link FrontUserController} 对应目录为 user）。 视图文件后缀为
     * .ftl，将视图映射的方法的名称的首字母变为大写，就是视图文件的名称。如 {@link FrontUserController#loginView()}
     * ，其对应的视图文件的名称为 user/LoginView.ftl。
     *
     * @param stes
     * @return
     */
    protected String ftl(StackTraceElement[] stes) {
        String prefix = StringUtils.remove(stes[1].getFileName(), "Controller.java");
        prefix=prefix.replaceFirst(prefix.substring(0, 1),prefix.substring(0, 1).toLowerCase());
        return prefix+ "/" + StringUtils.capitalize(stes[1].getMethodName());
    }
    
    /**
     * 重定向
     *
     * @param url
     * @return
     */
    protected String redirect(String url) {
        return "redirect:" + url;
    }
    
    /**
     * 判断用户是否为管理员（用户组为 group == 1）
     *
     * @param req
     * @return
     */
    protected boolean isAdmin(HttpServletRequest req) {
        return req.isUserInRole(SystemRole.ROLE_ADMIN.name());
    }
    
    /**
     * 获取登录用户 ID
     *
     * @return
     */
    public Integer getUserId() {
    	AdminUserVo su = (AdminUserVo) session.getAttribute("sysUser");
    	return null == su ? null : su.getId();
    }
 
    public void printJSON(Object obj) throws Exception{
    	response.setCharacterEncoding("UTF-8");  
    	response.setContentType("application/json; charset=utf-8");   
    	String result=JSONObject.toJSONString(obj);
    	print(result);
    }
    
    /**
     * Description:在调用Controller时，先执行@ModelAttribute方法
     * @auther:fdq
     * @date :2016年10月31日
     */
    @ModelAttribute  
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){  
        this.request = request;  
        this.response = response;  
        this.session = request.getSession();  
        response.addHeader("Access-Control-Allow-Origin", "*");
        System.out.println("request==========================="+request);
        System.out.println("response==========================="+response);
        System.out.println("session==========================="+session);
    }
    
    /**
     * 导出到excel
     * @author suker.zhou
     * @param wb
     * @throws IOException
     */
    public void export(HSSFWorkbook wb) throws IOException {
		response.setContentType("application/x-msdownload");

		response.setHeader("Content-Disposition", "attachment;filename="
				+ new Date().getTime() + ".xls");

		OutputStream output = response.getOutputStream();
		wb.write(output);
		output.flush();
		output.close();

	}
    
	public void print(String content){
		try {
			response.getWriter().print(content);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public PrintWriter getOut() throws Exception {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		return response.getWriter();
	}
	
	protected void sendHtml(String html) throws Exception{
		PrintWriter out = getOut();
		out.println(html);
		out.flush();
		out.close();
	}
}
